﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using DG.Tweening;

public class MatrixDragItem : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    //对应格子的 MatrixSpaceItem Index   0 - 8
    public int index;
    public string resultName;
    //对应行列Index
    public int rowIndex;
    public int colIndex;
    // Use this for initialization
    bool isCanDrag;
    Vector3 orgPos;
    int siblingIndex;
    RectTransform rt;
    Canvas canvas;
    Image itemSp;

    void Awake()
    {
        itemSp = transform.GetChild(0).GetComponent<Image>();
    }
    void Start()
    {
        isChangeAlpha = false;
        rt = gameObject.GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();
        //RectTransformUtility.ScreenPointToWorldPointInRectangle(canvas.transform as RectTransform, transform.position, canvas.worldCamera, out orgPos);
        orgPos = rt.position;
        siblingIndex = transform.GetSiblingIndex();
    }


    public void OnBeginDrag(PointerEventData eventData)
    {
        AudioManager.Instance.PlaySound(MatrixResType.audioPath + "603060102");
        if (!isCanDrag) return;
        transform.SetSiblingIndex(10);
        //Debug.Log(index + " ===index , rowIndex == "+ rowIndex+ "  , colIndex == "+ colIndex);
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (!isCanDrag) return;
        //Debug.Log(" OnDrag  ==================  "+ isCanDrag.ToString());
        Vector3 pos;

        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(canvas.transform as RectTransform, eventData.position, eventData.pressEventCamera, out pos))
        {
            rt.position = pos;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isCanDrag) return;
        Debug.Log(" OnEndDrag  ==================  ");
        //rt.position = orgPos;
        isCanDrag = false;
        transform.DOMove(orgPos, 0.15f).SetEase(Ease.Linear).OnComplete(() =>
        {
            AudioManager.Instance.PlaySound(MatrixResType.audioPath + "603060103");
            isCanDrag = true;
            transform.SetSiblingIndex(siblingIndex);
        });

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        //if (other.name.Contains("itembg_sp"))
        /*MatrixSpaceItem msi = other.GetComponent<MatrixSpaceItem>();
        if (isCanDrag && msi != null && msi.index == index && Vector3.Distance(transform.position,other.transform.position)<=0.3f)
        {
            Debug.Log("  OnTriggerEnter2D  ==========  " + msi.index);
            isCanDrag = false;
            EventSystem.current.SetSelectedGameObject(null);
            //AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "604030206");
            MatrixWindow.Instance.PlayTitleAnim(rowIndex, colIndex);
            transform.DOMove(other.transform.position, 0.3f).SetEase(Ease.Linear).OnComplete(() =>
            {
                MatrixWindow.Instance.AddCount(index);

            });
        }*/
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (isCanDrag)
        {
            MatrixSpaceItem msi = other.GetComponent<MatrixSpaceItem>();
            //&& msi.index == index
            if (msi != null && !msi.IsOwnPg && msi.resultName == resultName && Vector3.Distance(transform.position, other.transform.position) <= 5f)
            {
                //Debug.Log("  OnTriggerEnter2D  ==========  " + msi.index);
                isCanDrag = false;
                //AudioManager.Instance.PlaySound(Itempathinfo.puzzleGamePath + "604030206");
                GetColRowIndex(msi.index);
                MatrixWindow.Instance.PlayTitleAnim(rowIndex, colIndex);
                transform.DOMove(other.transform.position, 0.15f).SetEase(Ease.Linear).OnComplete(() =>
                {
                    AudioManager.Instance.PlaySound(MatrixResType.audioPath + "603060104");
                    MatrixWindow.Instance.AddCount(msi.index);

                });

            }
        }
    }
    public void SetItem(MatrixType type, string spriteName, int _index,int _rowIndex, int _colIndex, int _rotation)
    {                                                                      
        isCanDrag = false;
        index = _index;
        resultName = spriteName;
        rowIndex = _rowIndex;
        colIndex = _colIndex;
        string atlas = MatrixModel.Instance.GetAtlas(type);
        itemSp.color= new Color(1, 1, 1, 0);
        itemSp.gameObject.SetActive(true);        
        Image img = itemSp.GetComponent<Image>();
        //img.sprite = CommonUtility.GetSprite(atlas, spriteName);
        img.sprite = ResourceManager.Instance.GetResource(atlas + spriteName, typeof(Sprite), enResourceType.Prefab).m_content as Sprite;
        img.SetNativeSize();
        img.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, _rotation));
        Invoke("ChangeAlpha", 0.4f);
    }
    void ChangeAlpha()
    {
        isChangeAlpha = true;
    }
    bool isChangeAlpha;
    private void Update()
    {
        if (isChangeAlpha)
        {
            float alpha = Mathf.Lerp(itemSp.color.a, 1f, Time.deltaTime * 4f);
            itemSp.color = new Color(1, 1, 1, alpha);
            if (Mathf.Abs(itemSp.color.a - 1) < 0.05f)
            {
                itemSp.color = new Color(1, 1, 1, 1);
                isCanDrag = true;
                isChangeAlpha = false;
            }           
        }
    }
    public void ResetItem()
    {
        rt.position = orgPos;
        transform.SetSiblingIndex(siblingIndex);
        itemSp.gameObject.SetActive(false);
        //isCanDrag = true;
        DestroyImmediate(this);
    }

    void GetColRowIndex(int index)
    {
        switch (index)
        {
            case 0:
                rowIndex = 0;
                colIndex = 0;
                break;
            case 1:
                rowIndex = 0;
                colIndex = 1;
                break;
            case 2:
                rowIndex = 0;
                colIndex = 2;
                break;
            case 3:
                rowIndex = 1;
                colIndex = 0;
                break;
            case 4:
                rowIndex = 1;
                colIndex = 1;
                break;
            case 5:
                rowIndex = 1;
                colIndex = 2;
                break;
            case 6:
                rowIndex = 2;
                colIndex = 0;
                break;
            case 7:
                rowIndex = 2;
                colIndex = 1;
                break;
            case 8:
                rowIndex = 2;
                colIndex = 2;
                break;
        }
    }
}
